package com.qingyun.system.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.qingyun.system.service.ChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;


@Service
public class ChatServiceImpl implements ChatService {

    @Value("${dashscope.api-key}")
    private String apiKey;


    @Value("${dashscope.model-name}")
    private String modelName;
    /**
     * 聊天
     *
     * @param content 输入的文本
     * @return 智能机器人回复的JSON格式的文本
     */
    @Override
    public GenerationResult callWithMessage(String content)  {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("你是一个乐于助人的助手。 您可以通过回答我的问题来帮助我。 您还可以向我提问。默认用中文回答所有问题，除非特别情况。遇到有争议或者需求及时告诉我，毕竟我会犯错。")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(content)
                .build();
        GenerationParam param = GenerationParam.builder()
                .apiKey(apiKey)
                .model(modelName)
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.TEXT)
                .build();
        try {
            return gen.call(param);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(),e);
        }
    }
}
